package com.hcloud.gateway.captcha;

import com.wf.captcha.SpecCaptcha;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * @Auther hepangui
 * @Date 2018/10/27
 */
public class PngCaptcha extends SpecCaptcha {

    public PngCaptcha(int width, int height, int len) {
        super(width, height, len);
    }

    /**
     * 适应gateway，无法直接使用out
     * @return
     */
    public BufferedImage getPngImage() {
        this.checkAlpha();
        char[] strs = this.textChar();

        BufferedImage bi = new BufferedImage(this.width, this.height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = (Graphics2D) bi.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, this.width, this.height);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setStroke(new BasicStroke(1.3F, 0, 2));
        this.drawLine(3, g);
        this.drawOval(8, g);
        AlphaComposite ac3 = AlphaComposite.getInstance(3, 0.8F);
        g.setComposite(ac3);
        int hp = this.height - this.font.getSize() >> 1;
        int h = this.height - hp;
        int w = this.width / strs.length;
        int sp = (w - this.font.getSize()) / 2;

        for (int i = 0; i < strs.length; ++i) {
            g.setColor(new Color(20 + num(110), 20 + num(110), 20 + num(110)));
            int x = i * w + sp + num(3);
            int y = h - num(3, 6);
            if (x < 8) {
                x = 8;
            }

            if (x + this.font.getSize() > this.width) {
                x = this.width - this.font.getSize();
            }

            if (y > this.height) {
                y = this.height;
            }

            if (y - this.font.getSize() < 0) {
                y = this.font.getSize();
            }

            g.setFont(this.font.deriveFont(num(2) == 0 ? 0 : 2));
            g.drawString(String.valueOf(strs[i]), x, y);
        }

        return bi;


    }
}
